import {
  Column,
  Entity,
  ManyToMany,
  ManyToOne,
  JoinColumn,
  JoinTable,
  AfterLoad,
  OneToOne,
  PrimaryColumn,
  BeforeInsert,
  BeforeUpdate,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import * as moment from 'moment';
import { RoleEntity } from '../../role/entities/role.entity';
import { DepartmentEntity } from '../../department/entities/department.entity';
import { AccountEntity } from 'src/module/account/entities/account.entity';

@Entity({ name: 'user' })
export class UsersEntity {
  @PrimaryColumn()
  id: string = uuidv4();

  @Column({
    type: 'varchar',
    length: 30,
    nullable: false,
    unique: true,
  })
  username: string;

  @Column({
    type: 'varchar',
    length: 200,
    nullable: true,
  })
  headPicture: string;

  @AfterLoad()
  updateHeadPicture() {
    if (!this.headPicture)
      this.headPicture =
        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.alicdn.com%2Fi4%2F2204484777%2FO1CN01l3OVic1l9ufSylfAj_%21%212204484777.jpg&refer=http%3A%2F%2Fimg.alicdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1675046478&t=2f817922272f32dad56eb18044afe38f';
  }

  @Column({
    type: 'varchar',
    name: 'password',
    length: 100,
    nullable: false,
    select: false,
    comment: '密码',
  })
  password: string;

  @OneToOne(() => AccountEntity, (account) => account.user, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'account_id' })
  account: AccountEntity;

  @ManyToMany(() => RoleEntity, (role) => role.users)
  @JoinTable({ name: 'user_role' })
  roles: RoleEntity[];

  @ManyToOne(() => DepartmentEntity, (department) => department.users)
  @JoinColumn({ name: 'department_id' })
  department: DepartmentEntity;

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
